<template>
  <div class="roles">
    <base-template :breadList="['权限列表', '角色列表']">
      <el-row type="flex" justify="end">
        <el-button type="primary" @click=";(rolesDialogVisible = true), (isEdit = false)">添加角色</el-button>
      </el-row>
      <!-- 表格 -->
      <el-table :data="roleData" style="width: 100%" border stripe>
        <el-table-column label="~" type="expand" width="50">
          <!-- 展开 -->
          <template v-slot="scope">
            <el-row v-for="(item, index) in scope.row.children" :key="item.id" type="flex" align="middle" class="borderBottom" :class="index == 0 ? 'borderTop' : ''">
              <el-col :span="6" class="flexCenter">
                <el-tag closable  @close='closeTag(scope.row,item)'>{{ item.authName }}</el-tag>
              </el-col>
              <el-col :span="18">
                <el-row v-for="(i, j) in item.children" :key="i.id" type="flex" align="middle" :class="j == 0 ? '' : 'borderTop'">
                  <el-col :span="8">
                    <el-tag closable type="success"  @close='closeTag(scope.row,i)'>{{ i.authName }}</el-tag>
                  </el-col>
                  <el-col :span="16">
                    <el-tag class="endRow" v-for="j in i.children" :key="j.id" closable type="danger" @close='closeTag(scope.row,j)'>{{ j.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="60"> </el-table-column>
        <el-table-column prop="roleName" label="用户名"> </el-table-column>
        <el-table-column prop="roleDesc" label="用户岗位"> </el-table-column>
        <el-table-column label="操作" width="240">
          <template v-slot="scope">
            <el-button size="mini" type="primary" @click="editRoles(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="removeRoles(scope.row)">删除</el-button>
            <el-button size="mini" type="warning" @click='allotRight(scope.row)'>分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </base-template>
    <!-- 添加角色弹窗 -->
    <el-dialog title="添加角色" :visible.sync="rolesDialogVisible" width="40%" :before-close="handleClose">
      <el-form ref="addRolesForm" :model="rolesForm" label-width="100px" status-icon :rules="rules">
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述：">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitRoles">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改权限" :visible.sync="allotDialogVisible" width="40%" :before-close="handleClose">
<!-- tree节点 -->
      <el-tree :data="treeData" show-checkbox node-key="id"  :default-checked-keys="defaultChecked"
	  :default-expand-all='true'  :props="defaultProps" ref='treeRef'> </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitNode">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BaseTemplate from '../../component/base-template.vue'
export default {
  components: {
    BaseTemplate,
  },
  data() {
    return {
      roleData: [],
      rolesForm: {
        //添加角色绑定对象
        roleName: '',
        roleDesc: '',
      },
      rules: {
        roleName: [{ required: true, message: '请填写角色名称', trigger: 'blur' }],
      },
      rolesDialogVisible: false,
      isEdit: true, //区分添加  or  修改
      editId: '',

      allotDialogVisible: false,
      treeData: [],
	  defaultProps:{
		  label:'authName',
		  children:'children',
	  },
	  defaultChecked:[],//树状图选中节点
	  editTreeId:'',
    }
  },
  created() {
    this.getRoleData()
  },
  methods: {
    getRoleData() {
      this.$store.dispatch('getRequest', { path: '/roles' }).then((res) => {
        this.roleData = res
      })
    },
    submitRoles() {
      //添加角色
      if (this.editId) {
        this.$store.dispatch('putRequest', { path: `/roles/${this.editId}`, params: this.rolesForm }).then((res) => {
          if (Object.prototype.toString.call(res) == '[object Object]') {
            this.getRoleData()
            this.$message.success('修改成功')
          } else {
            this.$message.error('修改失败')
          }
        })
      } else {
        this.$refs.addRolesForm.validate(async (valid) => {
          if (valid) {
            const res = await this.$store.dispatch('postRequest', { path: '/roles', params: this.rolesForm })
            if (res) {
              this.$message.success('添加角色成功')
              this.getRoleData()
            } else {
              this.$message.error('添加角色失败')
            }
            this.$refs.addRolesForm.resetFields()
          }
        })
      }
      this.clearStatus()
    },
    removeRoles(row) {
      //删除
      this.$confirm('确认关闭？')
        .then((_) => {
          this.$store.dispatch('deleteRequest', { path: `/roles/${row.id}` }).then((meta) => {
            if (meta.status == 200) {
              this.getRoleData()
              this.$message.success('删除成功')
            } else {
              this.$message.error('删除失败')
            }
          })
          done()
        })
        .catch((_) => {})
    },
    editRoles(row) {
      this.rolesForm.roleName = row.roleName
      this.rolesForm.roleDesc = row.roleDesc
      this.rolesDialogVisible = true
      this.editId = row.id
    },
    handleClose() {
      this.clearStatus()
    },
    clearStatus() {
        this.$refs.addRolesForm.resetFields()  //roleDesc 清除无效   可以初始化状态
      for (let prop in this.rolesForm) {
        this.rolesForm[prop] = ''
      }
      this.editId = null
      this.rolesDialogVisible = false
	  this.allotDialogVisible=false
    },
	async allotRight(row){
		this.allotDialogVisible=true
		this.getNodeId(row)
		this.editTreeId=row.id
		this.treeData=await this.$store.dispatch('getRequest',{path:`/rights/tree`})
		
	},
	getNodeId(para){
		this.defaultChecked=[]
		let  _getNodeId=(node)=>{
			if(!node.children){
				this.defaultChecked.push(node.id)
			}else{
				for(let prop in node.children){
					_getNodeId(node.children[prop])
				}
			}
		}
		 _getNodeId(para)
	},
	async closeTag(roleId,rightId){   //删除个别权限
	
	
		const {meta,data}=await this.$axios.delete(`/roles/${roleId.id}/rights/${rightId.id}`)
		if(meta.status==200){

			roleId.children=data  //重新赋值权限，防止刷新
			console.log(data,);
			this.$message.success('删除权限成功')
		}else{
			this.$message.error('删除权限失败')
		}
	},
	async submitNode(){
		let  key1=this.$refs.treeRef.getHalfCheckedKeys()
		let  key2=this.$refs.treeRef.getCheckedKeys()
		const temp=[...key1,...key2].join(',')
		const {meta,data}=await this.$store.dispatch('postRequest',{path:`/roles/${this.editTreeId}/rights`,params:{rids:temp}})
		
		if(meta.status==200){
			this.$message.success('分配权限成功')
			this.allotDialogVisible=false
			this.getRoleData()
		}else{
			this.$message.error('分配权限失败')
		}
		
	}		
  },
}
</script>

<style lang="less" scoped>
.el-row {
  // margin: 10px 0;
  padding: 5px 0;
  &.borderTop {
    border-top: 1px solid #ddd;
  }
  &.borderBottom {
    border-bottom: 1px solid #ddd;
  }
  .el-col.flexCenter {
    display: flex;
    justify-content: center;
  }
  .el-tag {
    margin: 10px;
  }
}
</style>
